import { Select } from 'antd'
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import axios from '../../controllers/request'
import './styles.css'

/*
obj :{name:xxx,type:xxx} 参数
selectWidth：宽度
portName：api 接口
defValue：初始值
onChange：返回值（val = id, item = 所有内容）

import SelectScroll from '@/components/select/SelectScroll'

<SelectScroll
  selectWidth={'140px'}
  portName={'/api/v1/prompt_plt/query'}
  obj={{}}
  defValue={''}
  onChange={onChange}
></SelectScroll>
*/
export default function SelectScroll({ obj, selectWidth, portName, defValue, onChange }) {
  const { t } = useTranslation()

  // 页码，及搜索值变化时，发请求
  const [options, setOptions] = useState([])
  const [paramsObj, setParamsObj] = useState({
    page_num: 1,
    page_size: 10,
    total: 0
  })
  useEffect(() => {
    setParamsObj({
      ...paramsObj,
      ...obj
    })
    axios
      .get(`${portName}`, {
        params: {
          ...paramsObj,
          ...obj
        }
      })
      .then((res: any) => {
        setParamsObj({
          ...paramsObj,
          total: res.total
        })
        setOptions([...options, ...res.data])
      })
  }, [paramsObj.page_num])
  const scrollEnd = e => {
    e.persist()
    console.log('API Scroll End')
    const { target } = e
    // 滚动 触底 看接口是否还有剩余的值没传过来
    if (target.scrollTop + target.offsetHeight === target.scrollHeight) {
      if (paramsObj.page_num * paramsObj.page_size < paramsObj.total) {
        setParamsObj({
          ...paramsObj,
          page_num: paramsObj.page_num + 1
        })
      }
    }
  }
  // 搜索条件变化时，current变成1，
  // const searchDataset = value => {
  //   setParamsObj({
  //     ...paramsObj,
  //     page_num: 1
  //   })
  // }
  return (
    <div className="select-scroll-select-box">
      <Select
        defaultValue={defValue || null}
        placeholder={t('call.callTemName')}
        options={options}
        style={{ width: selectWidth }}
        fieldNames={{ label: 'name', value: 'id' }} // 与options中的key 值
        onPopupScroll={scrollEnd}
        onChange={(val, item) => onChange(val, item)}
        // showSearch
        // onSearch={debounce(searchDataset, 500)} // 防止频繁触发请求
      ></Select>
    </div>
  )
}
